package com.sofwin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sofwin.dto.UserDto;
import com.sofwin.mapper.SysUserMapper;
import com.sofwin.pojo.SysUser;
import com.sofwin.pojo.SysUserExample;
import com.sofwin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;

/**
 * @packageName: com.sofwin.service.impl
 * @user: andyliu
 * @date: 2022/12/29 9:44
 * @email 115176513@qq.com
 * @description: TODO
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private SysUserMapper mapper;

    @Override
    public boolean saveOrUpdateUser(SysUser user) {
        // 新增和更新的区别？？？ 是否有id
        if(user.getId()!=null){
           return  mapper.updateByPrimaryKeySelective(user)==1?true:false;
        }
        return mapper.insertSelective(user)==1?true:false;
    }

    @Override
    public SysUser queryById(Integer id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public boolean removeById(Integer id) {
        return mapper.deleteByPrimaryKey(id)==1?true:false;
    }

    // 不能循环调用removeById
    // 事务
    @Override
    public boolean removeByIds(Integer[] ids) {
        SysUserExample example = new SysUserExample();
        SysUserExample.Criteria criteria = example.createCriteria();
        criteria.andIdIn(Arrays.asList(ids));
        int num = mapper.deleteByExample(example);
        return num==ids.length?true:false;
    }

    @Override
    public PageInfo<UserDto> queryUsers(Integer pageNumber, Integer pageSize, SysUser user) {
        PageHelper.startPage(pageNumber,pageSize);
        List<UserDto> users = mapper.selectUsers(user);
        return new PageInfo<UserDto>(users);
    }

    @Override
    public SysUser queryUserByLoginNameAndPwd(String loginName, String loginPwd) {
        SysUserExample example = new SysUserExample();
        SysUserExample.Criteria criteria = example.createCriteria();
        criteria.andLoginNameEqualTo(loginName);
        if(!StringUtils.isEmpty(loginPwd)) {
            criteria.andLoginPwdEqualTo(loginPwd);
        }
        List<SysUser> sysUsers = mapper.selectByExample(example);
        if(sysUsers!=null && sysUsers.size()==1){
            return  sysUsers.get(0);
        }
        return null;
    }
}
